﻿using BootstrapBlazor.Components;
using CodeMan.Application.Contracts;
using CodeMan.Application.Contracts.ClassGens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeMan.Data.DataServiceBaseExts
{
    /// <summary>
    /// 实体类扩展
    /// 用于数据新增，修改，删除服务
    /// </summary>
    public static class ClassAttributeDTOExts
    {
        public static bool Query<TModel>(this ClassAttributeDTO model, IEnumerable<TModel> items)
        {
            if (!string.IsNullOrEmpty(model.AName)) items = items.Cast<ClassAttributeDTO>().Where(item => item.AName?.Contains(model.AName, StringComparison.OrdinalIgnoreCase) ?? false).Cast<TModel>();
            if (!string.IsNullOrEmpty(model.ADesc)) items = items.Cast<ClassAttributeDTO>().Where(item => item.ADesc?.Contains(model.ADesc, StringComparison.OrdinalIgnoreCase) ?? false).Cast<TModel>();
            var isSearched = !string.IsNullOrEmpty(model.AName) || !string.IsNullOrEmpty(model.ADesc);

            return isSearched;
        }

        public static bool Save<TModel>(this ClassAttributeDTO model, List<TModel> Items)
            where TModel : class, new()
        {
            var item = Items?.FirstOrDefault(item =>
            {
                var f = item as ClassAttributeDTO;
                return f.AName == model.AName;
            });
            if (item == null)
            {
                var id = Items!.Count() + 1;
                while (Items.FirstOrDefault(item => (item as ClassAttributeDTO)!.ClassGenId == id) != null)
                {
                    id++;
                }
                item = new ClassAttributeDTO()
                {
                    ClassGenId = id,
                    AName = model.AName,
                    ADesc = model.ADesc,
                    AType = model.AType,
                    defaultValue = model.defaultValue,
                    Length = model.Length


                } as TModel;
                Items?.Add(item!);
            }
            else
            {
                var f = item as ClassAttributeDTO;
                f.AName = model.AName; 
                f.ADesc = model.ADesc;
                f.AType = model.AType;
                f.defaultValue = model.defaultValue;
                f.SortNo = model.SortNo;
                f.Length = model.Length;
            }
            return true;
        }
    }
}
